package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ObjectMapper objectMapper;

    private void handlerBoolQueryBuilder(SearchRequest request, RequestParams params) {
        //1.使用 boolean 查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1) 查询
        String searchContent = params.getKey();
        if(!StringUtils.hasLength(searchContent)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", searchContent));
        }
        // 2) 城市过滤
        String city = params.getCity();
        if(StringUtils.hasLength(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        // 3) 品牌过滤
        String brand = params.getBrand();
        if(StringUtils.hasLength(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 4) 星级过滤
        String star = params.getStarName();
        if(StringUtils.hasLength(star)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", star));
        }
        // 5) 价格范围过滤
        if(params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders
                    .rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }

        //2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询，相关性算分查询
                boolQueryBuilder,
                //function score 的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中的一个 function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        request.source().query(functionScoreQuery);
    }

    @Override
    public PageResult search(RequestParams params) {
        try {
            //1.创建请求
            SearchRequest request = new SearchRequest("hotel");
            //2.准备参数
            handlerBoolQueryBuilder(request, params);
            //3.分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            if(page == null || size == null) {
                throw new IOException("分页数据不能为空！");
            }
            request.source().from((page - 1) * size).size(size);
            //4.根据距离排序
            if (params.getLocation() != null) {
                request.source().sort(SortBuilders.geoDistanceSort("location",
                                new GeoPoint(params.getLocation()))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }
            //5.发送请求，接收响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //6.解析响应
            return handlerResponse(response);
        } catch (IOException e) {
            System.out.println("[HotelService] 搜索失败！");
            e.printStackTrace();
            return null;
        }
    }

    private PageResult handlerResponse(SearchResponse response) throws JsonProcessingException {
        //1.解析结果
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        List<HotelDoc> hotelDocList = new ArrayList<>();
        for(SearchHit searchHit : hits1) {
            //获取source
            String json = searchHit.getSourceAsString();
            HotelDoc hotelDoc = objectMapper.readValue(json, HotelDoc.class);
            Object[] sortValues = searchHit.getSortValues();
            //通过 getSortValues 得到的是一个 Object 类型数组，因为有可能是根据多个条件排序(价格、评价、距离...)
            //获取的下标，就要看你先给谁排序，谁就是 0 下标(以此类推)
            if(sortValues != null && sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }
            hotelDocList.add(hotelDoc);
        }
        return new PageResult(total, hotelDocList);
    }


    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //1.构造请求
            SearchRequest request = new SearchRequest("hotel");
            //2.准备参数
            // 1) 查询
            handlerBoolQueryBuilder(request, params);
            // 2) 设置 size
            request.source().size(0);
            // 3)聚合
            buildAggregation(request);
            //3.发送请求，接收响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.处理响应
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> brandAgg = getAggListByName(aggregations, "brandAgg");
            result.put("brand", brandAgg);
            List<String> cityAgg = getAggListByName(aggregations, "cityAgg");
            result.put("city", cityAgg);
            List<String> starAgg = getAggListByName(aggregations, "starAgg");
            result.put("starName", starAgg);
            return result;
        } catch (IOException e) {
            System.out.println("[HotelService] 酒店数据聚合失败！");
            e.printStackTrace();
            return null;
        }
    }

    private List<String> getAggListByName(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        // 1) 聚合品牌
        request.source().aggregation(
                AggregationBuilders
                        .terms("brandAgg")
                        .field("brand")
                        .size(100)
        );
        // 2) 聚合城市
        request.source().aggregation(
                AggregationBuilders
                        .terms("cityAgg")
                        .field("city")
                        .size(100)
        );
        //3) 聚合星级
        request.source().aggregation(
                AggregationBuilders
                        .terms("starAgg")
                        .field("starName")
                        .size(100)
        );
    }

    @Override
    public List<String> suggestion(String prefix) {
        try {
            //1.创建请求
            SearchRequest request = new SearchRequest("hotel");
            //2.准备参数
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "mySuggestion",
                    SuggestBuilders
                            .completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //3.发送请求，接收响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析响应(处理自动补全结果)
            Suggest suggest = response.getSuggest();
            List<String> suggestionList = new ArrayList<>();
            if(suggest != null) {
                CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
                for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                    String text = option.getText().toString();
                    suggestionList.add(text);
                }
            }
            return suggestionList;
        } catch (IOException e) {
            System.out.println("[HotelService] 自动补全失败！prefix=" + prefix);
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void insertHotelById(Long id) {
        try {
            Hotel hotel = getById(id);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            String hotelDocJson = objectMapper.writeValueAsString(hotelDoc);
            //1.构建请求
            IndexRequest request = new IndexRequest("hotel").id(id.toString());
            //2.准备参数
            request.source(hotelDocJson, XContentType.JSON);
            //3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            System.out.println("[HotelService] 酒店数据插入或修改失败! id=" + id);
            e.printStackTrace();
        }
    }

    @Override
    public void deleteHotelById(Long id) {
        try {
            //1.创建请求
            DeleteRequest request = new DeleteRequest("hotel" , id.toString());
            //2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch(Exception e) {
            System.out.println("[HotelService] 酒店数据删除失败！id=" + id);
            e.printStackTrace();
        }
    }
}
